package com.ypf.accesslimit.limit;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class AccessLimiterImpl implements AccessLimiter{

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 传入的是boundingKey 和 限流策略的key是不一样的
     * @param key  限制接口的标识
     * @param times 访问次数
     * @param per 一段时间
     * @param unit 时间单位
     * @return
     */
    @Override
    public boolean isLimited(String key, Long times, Long per, TimeUnit unit) {
        // 根据专门储存访问次数的key 将里面的数值加1
        Long curTimes = redisTemplate.boundValueOps(key).increment(1);
        log.info("curTimes: {}",curTimes);
        if (curTimes>times){
            log.error("超频访问:[{}]",key);
            return true;
        }else {
            if (curTimes == 1){
                log.info(" set expire");
                redisTemplate.boundGeoOps(key).expire(per,unit);

            }
            return false;
        }
    }

    @Override
    public void addLimitInfo(String redisKey, HashMap map) {
        redisTemplate.opsForHash().putAll(redisKey,map);
    }

    @Override
    public HashMap getLimitInfo(String redisKey) {
        HashMap<Object,Object> map = (HashMap<Object, Object>) redisTemplate.opsForHash().entries(redisKey);
        return map;
    }

    @Override
    public void deleteLimited(String key) {
        // 因为不能直接删除这个hash 所以只能指定参数删除
        redisTemplate.opsForHash().delete(key,"times","unit","per");
    }


}
